import json
import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse

from domain.consts import user_context
from domain.resp import Resp
from api import eshop_assistant_api

app = FastAPI()
registered_routes = [route.path for route in eshop_assistant_api.router.routes]
white_list = ["/api/login","/api/getUserInfo"]

@app.middleware("http")
async def add_request_to_context(request: Request, call_next):
    user_id = request.headers.get("useraccountid")
    if not user_id and request.url.path in registered_routes and request.url.path not in white_list:
        return JSONResponse(Resp.error(code = 501, msg="not login"))
    user_context.set(user_id)
    response = await call_next(request)
    return response

def set_app_corsmiddleware(config: dict):
    """跨域设置"""
    origins = config.get("origins") or ["*"]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )


def set_app_exception_handlers():
    async def request_validation_exception_handler(
            request: Request, exc: RequestValidationError
    ) -> JSONResponse:
        """捕捉422报错并进行自定义处理"""
        error_json = await request.json()
        print(error_json)
        return Resp.error(msg = json.dumps(exc.errors()))

    app.add_exception_handler(RequestValidationError, request_validation_exception_handler)


def set_router_api():
    app.include_router(eshop_assistant_api.router, tags=["电商运营助手接口"])


if __name__ == "__main__":
    set_router_api()
    set_app_corsmiddleware({})
    uvicorn.run(app, host='0.0.0.0', port=38888)
